<template>
  <div class="total">
    <ListTitle list-title="空域运行安全评估"></ListTitle>
    <div class="table-choice">
      <button @click="selectRoute" :class="['button', { active: selectedButton === 'route' }]">
        <span class="text_button">航路</span>
      </button>
      <button @click="selectUpdown" :class="['button', { active: selectedButton === 'updown' }]">
        <span class="text_button">起降区</span>
      </button>
      <button @click="selectTask" :class="['button', { active: selectedButton === 'task' }]">
        <span class="text_button">作业区域</span>
      </button>
    </div>
    <div class="layout2">
      <div class="layout1" style="margin-right: 0.3rem;">
        <!-- 顶部控制区域 -->
        <div class="top-controls">
          <!-- 评估模型选择区域 -->
          <div class="model-selection">
            <!-- <FormComponent :formData="formDataSafety" :selectedType.sync="selectedType" :selectedButton="selectedButton" @run-clicked="handleRun" /> -->
            <FormComponent :formData="formDataSafety" :selectedType.sync="selectedType" :selectedButton="selectedButton"
              @run-clicked="handleRun" @loading-finished="onLoadingFinished" />

          </div>
        </div>

        <!-- 安全间隔显示区域 -->
        <div class="form-container" v-loading="loading_fu">
          <div class="title_plat">
            <img referrerpolicy="no-referrer" src="../assets/img/module4/part1/image1.png" class="image_1">
            <span class="text_form">横向安全间隔（m）</span>
          </div>
          <div class="plat-form">
            <ManagementPlatform :aircraftTypes="[
              { name: '小型机', values: this.showlist1 },
              { name: '中型机', values: this.showlist2 },
              { name: '大型机', values: this.showlist3 },
              { name: 'eVTOL', values: this.showlist4 }
            ]" />
          </div>
          <div class="title_plat">
            <img referrerpolicy="no-referrer" src="../assets/img/module4/part1/image1.png" class="image_1">
            <span class="text_form">纵向安全间隔（m）</span>
          </div>
          <div class="plat-form">
            <ManagementPlatform :aircraftTypes="[
              { name: '小型机', values: this.showlist5 },
              { name: '中型机', values: this.showlist6 },
              { name: '大型机', values: this.showlist7 },
              { name: 'eVTOL', values: this.showlist8 }
            ]" />
          </div>
          <div class="title_plat">
            <img referrerpolicy="no-referrer" src="../assets/img/module4/part1/image1.png" class="image_1">
            <span class="text_form">垂直安全间隔（m）</span>
          </div>
          <div class="plat-form">
            <ManagementPlatform :aircraftTypes="[
              { name: '小型机', values: this.showlist9 },
              { name: '中型机', values: this.showlist10 },
              { name: '大型机', values: this.showlist11 },
              { name: 'eVTOL', values: this.showlist12 }
            ]" />
          </div>
        </div>

        <!-- 右侧空白区域，为将来扩展预留 -->

        <!-- <div class="right-section">
          右侧内容将来添加
        </div> -->
      </div>
      <div class="layout1">
        <FormComponentCapacity style="height: 100%;" :formData="formDataCapacity" :type="type" :label1="label1"
          :label2="label2" :label3="label3" :safedis="safedis" :accLabel="accLabel" :monitor_num="monitor_num"
          :post_ui="post_ui" @submit="submitForm" @reset="resetForm" @visiable_fu="receivedata" @showif_fu="handle_show"
          :selectedRow="selectedRow" :object_post="object_post" :safety_ui="safety_ui" :if_visiable="if_visiable"
          :show_if="show_if" :label1_l="label1_l" :label2_l="label2_l" :accLabel_l="accLabel_l"
          :monitor_num_l="monitor_num_l" :airspace="airspace" :airspace_l="airspace_l" />
      </div>
    </div>
  </div>
</template>

<script>
import ListTitle from "@/components/ListTitle";
import ManagementPlatform from '@/components/plat_table.vue';
import axios from 'axios';
import FormComponent from '@/components/Form4Safety.vue';
import FormComponentCapacity from '@/components/Form4Capacity.vue';

const baseApi = process.env.NODE_ENV === 'production'
  ? '/api'  // 使用代理路径
  : 'http://192.168.0.135:30027'
  // : process.env.VUE_APP_REMOTE_API_MODULE4;

export default {
  name: "Module4SafetyCapacity",
  components: {
    ManagementPlatform,
    ListTitle,
    FormComponent,
    FormComponentCapacity
  },
  data() {
    return {
      order: null,
      tableData: [],
      formData: [],
      formDataSafety: [],
      formDataCapacity: [],
      name_label: "起降区名称",
      showContent: false,
      showNewInput: false,
      row: null,
      searchKeyword: '',
      matchitem: [],
      // selectedRow: null,
      api_post: '',
      name_option1: true,
      name_option2: false,
      name_option3: false,
      showlist1: [],
      showlist2: [],
      showlist3: [],
      showlist4: [],
      showlist5: [],
      showlist7: [],
      showlist6: [],
      showlist8: [],
      showlist9: [],
      showlist10: [],
      showlist11: [],
      showlist12: [],
      showlist13: [],
      showlist14: [],
      showlist15: [],
      showlist16: [],
      splitData: [],
      quiry_ui: `${baseApi}/takeoffland/search`,
      selectedButton: 'updown', // 默认高亮'起降区'按钮
      typeOptions: [
        { value: 0, label: '小型' },
        { value: 1, label: '中型' },
        { value: 2, label: '大型' }
      ], // 用于存储动态更新的类型选项
      // 以下是类型定义
      airspaceTypes: {
        updown: [
          { value: 0, label: '小型' },
          { value: 1, label: '中型' },
          { value: 2, label: '大型' }
        ],
        route: [
          { value: 0, label: '低速' },
          { value: 1, label: '中速' },
          { value: 2, label: '高速' },
          { value: 3, label: '匝道' }
        ],
        task: [
          { value: 0, label: '即时配送' },
          { value: 1, label: '科技文旅' },
          { value: 2, label: '城市治理' },
          { value: 3, label: '立体交通' },
          { value: 4, label: '边境管控' }
        ]
      },
      loading_fu: false,
      type: '类型', // 默认值为"类型"
      label1: '起飞降落坪数量', // 默认值为"起飞降落坪数量"
      label1_l: '个', // 默认值为"个"
      label2: '进离场点高度', // 默认值为"进离场点高度"
      label2_l: "m", // 默认值为"m"（米）
      label3: '', // 默认为空字符串
      accLabel: '导航精度误差', // 默认值为"导航精度误差"
      accLabel_l: 'm', // 默认值为"m"（米）
      monitor_num: '监视容量', // 默认值为"监视容量"
      monitor_num_l: '架次', // 默认值为"架次"
      safedis: '安全间隔', // 默认值为"安全间隔" 
      airspace: "", // 默认为空字符串
      airspace_l: '', // 默认为空字符串
      if_visiable: true, // 默认为true
      show_if: false, // 默认为false
      object_post: {}, // 默认为空对象
      post_ui: `${baseApi}/takeoffland/capacityeval`, // 默认值为API路径
      safety_ui: `${baseApi}/takeoffland/idsafeintervalall`, // 默认值为API路径
      selectedType: 1, // 默认值为1
    };
  },
  created() {
    // this.fetchFormData(`${baseApi}/takeoffland/idsafeintervalall`);
    // selectRoute();
  },
  mounted() {
    this.selectRoute();
  },
  computed: {
    selectedRow() {
      return this.formData[this.selectedType];
    },
  },
  methods: {
    async fetchFormData(api_post) {
      console.log("fetchFormData  执行")
      try {
        const response = await axios.get(api_post)
        console.log(response.data);
        if (response.data.code === 0) {
          this.formData = response.data.data;
          console.log("fetchFormData  执行完成,done")
          console.log(response.data);
        }
      }
      catch (error) {
        console.error('获取数据失败', error);
      }
    },
    async handleRun(payload) {
      console.log("handleRun 执行")
      console.log("选中的模型是：", payload.selectedModels);

      if (this.formData && this.formData.length > 0) {
        // 使用第一个可用的数据作为默认值
        this.getSplitDataById(this.formData[this.selectedType].id, payload.selectedModels);
        // 使用类型 id 作为默认值
        // this.getSplitDataById(this.selectedType, payload.selectedModels);
      }
    },
    getSplitDataById(id, selectedModels) {
      console.log('开始分割数据,被分割的this.formData id', this.formData, id)

      const matchedItem = this.formData.find((item) => item.id === id);
      if (!matchedItem) return;

      // 1. 统计选中模型数量
      const selectedCount = Object.values(selectedModels).filter(Boolean).length;

      // 2. 根据数量确定缩放系数
      let scale = 1;
      if (selectedCount === 1) scale = 0.7;
      else if (selectedCount === 2) scale = 0.75;
      else if (selectedCount === 3) scale = 0.8;
      else if (selectedCount === 4) scale = 0.85;

      // 3. 缩放 safeInterval 数据（3维数组：3 x 4 x N）
      const scaledSafeInterval = matchedItem.safeInterval.map(row =>
        row.map(list =>
          list.map(val => (typeof val === 'number' ? (val * scale).toFixed(2) : val))
        )
      );

      // 4. 赋值到对应显示数组
      [
        this.showlist1, this.showlist2, this.showlist3, this.showlist4,
        this.showlist5, this.showlist6, this.showlist7, this.showlist8,
        this.showlist9, this.showlist10, this.showlist11, this.showlist12
      ] = scaledSafeInterval.flat();
    },
    selectUpdown() {
      this.resetForm();
      this.selectedButton = 'updown';
      this.typeOptions = this.airspaceTypes.updown;
      this.name_label = "起降区名称";
      this.fetchFormData(`${baseApi}/takeoffland/idsafeintervalall`);
      this.selectedButton = 'updown';
      this.typeOptions = this.airspaceTypes.updown;
      this.fetchTableData(`${baseApi}/takeoffland/search`);
      this.safety_ui = `${baseApi}/takeoffland/idsafeintervalall`;
      this.update_ui = `${baseApi}/takeoffland/update`;
      this.quiry_ui = `${baseApi}/takeoffland/search`;
      this.post_ui = `${baseApi}/takeoffland/capacityeval`;
      this.type = '类型';
      this.label1 = '起飞降落坪数量';
      this.label1_l = '个';
      this.label2 = '进离场点高度';
      this.label2_l = 'm';
      this.safedis = '安全间隔';
      this.accLabel = '导航精度误差';
      this.accLabel_l = 'm';
      this.monitor_num = '监视容量';
      this.monitor_num_l = '架次';
      this.if_visiable = true;
      this.show_if = false;
      this.showButton = false;
      this.airspace = null;
      this.airspace_l = null;
      // this.resetForm()
    },
    selectRoute() {
      this.resetForm();
      this.selectedButton = 'route';
      this.typeOptions = this.airspaceTypes.route;
      this.name_label = "航路名称";
      // this.fetchFormData(`${baseApi}/airlane/idsafeintervalall`);
      this.fetchFormData(`${baseApi}/workzone/idsafeintervalall`);
      this.selectedButton = 'route';
      this.typeOptions = this.airspaceTypes.route;
      this.quiry_ui = `${baseApi}/airlane/search`;
      // this.fetchTableData(`${baseApi}/airlane/search`);
      this.fetchTableData(`${baseApi}/workzone/search`);
      this.safety_ui = `${baseApi}/airlane/idsafeintervalall`;
      this.post_ui = `${baseApi}/capacity/assess`;
      this.type = '类型';
      this.label1 = '重复次数';
      this.label1_l = ''
      this.label2 = '仿真步长';
      this.label2_l = 's'
      this.showButton = false;
      this.show_if = false;
      this.if_visiable = true;
      this.safedis = '安全间隔';
      this.accLabel = '放行时间';
      this.accLabel_l = 'min';
      // this.monitor_num = '安全间隔裕量';
      // this.monitor_num_l = 'km';
      this.monitor_num = '';
      this.monitor_num_l = '';
      this.airspace = null;
      this.airspace_l = null;
      // this.resetForm()
    },
    selectTask() {
      this.resetForm();
      this.selectedButton = 'task';
      this.typeOptions = this.airspaceTypes.task;
      this.name_label = "工作区名称";
      this.fetchFormData(`${baseApi}/workzone/idsafeintervalall`);
      this.selectedButton = 'task';
      this.typeOptions = this.airspaceTypes.task;
      this.quiry_ui = `${baseApi}/workzone/search`;
      this.safety_ui = `${baseApi}/workzone/idsafeintervalall`;
      this.fetchTableData(`${baseApi}/workzone/search`);
      this.post_ui = `${baseApi}/workzone/capacityeval`;
      this.type = '类型';
      this.if_visiable = true;
      this.show_if = false;
      this.label1 = '作业种类';
      this.label1_l = '';
      this.label2 = '';
      this.showButton = false;
      this.label2_l = '';
      this.safedis = '安全间隔';
      this.monitor_num = '监视容量';
      this.monitor_num_l = '架次';
      this.accLabel = '导航精度误差';
      this.accLabel_l = 'm';
      this.airspace = "区域高度区间";
      this.airspace_l = 'm';
      // this.resetForm()
    },
    resetForm() {
      this.formData = [];
      this.showlist1 = [];
      this.showlist2 = [];
      this.showlist3 = [];
      this.showlist4 = [];
      this.showlist5 = [];
      this.showlist6 = [];
      this.showlist7 = [];
      this.showlist8 = [];
      this.showlist9 = [];
      this.showlist10 = [];
      this.showlist11 = [];
      this.showlist12 = [];
    },
    receivedata(isVisiable) {
      this.showButton = !isVisiable;
    },
    handle_show(isshow) {
      this.show_if = isshow;
    },
    callChildMethod() {
      this.show_if = false;
      // this.showButton=false;
    },
    async handleSearch() {

      this.keytext = this.searchKeyword;
      await this.fetchAirspaceDemand();
    },

    async fetchAirspaceDemand() {
      try {
        const params = {};
        if (this.order == 0 || this.order == 1 || this.order == 2) {
          const orderAsInt = parseInt(this.order, 10);
          if (!isNaN(orderAsInt)) {
            params.type = orderAsInt;
          }
        }

        if (this.keytext) {
          params.index = this.keytext;
        }

        console.log("查询数据", params)
        const response = await axios.get(this.quiry_ui, { params });
        this.tableData = response.data.data;
        console.log("airspaceDemand接口返回的数据", response.data.data)
      } catch (error) {
        console.error('Error fetching airspace demand:', error);
      }
    },
    async fetchTableData(api_post) {
      console.log("fetchTableData  执行")
      try {
        console.log("fetchTableData  开始执行")
        const response = await axios.get(api_post)
        console.log("fetchTableData  执行完成")
        if (response.data.code === 0) {
          this.tableData = response.data.data;
          console.log(response.data);
          console.log("fetchTableData  执行完成,done")
          console.log(response.data.data);
        }
      }
      catch (error) {
        console.error('获取数据失败', error);
      }

    },
    displayRowData(row) {
      this.selectedRow = row;
      this.object_post = row;
      this.show_if = true;
      this.showButton = false;
      this.parent_bool = true;
      console.log("选中的行", row)
    },
    submitForm() {
      console.log('提交表单数据', this.formData);
    },
    onLoadingFinished() {
      this.handleRun({
        selectedModels: {
          event: true,
          fault: true,
          reich: true,
          cross: true
        }
      });
    }
  }
};
</script>

<style scoped>
h1 {
  color: #ffffff;
}

.total {
  display: flex;
  height: 100%;
  width: 100%;
  flex-direction: column;
}

.table-choice {
  display: flex;
  margin-top: 0.2rem;
  height: 2.25rem;
  width: 100%;
}

.button {
  display: flex;
  height: 2.25rem;
  background: url(../assets/img/module4/part1/SketchPng672f442656b7e0f3c9863869768a199363cee97583efcf5fc791168bad3b2f9f.png) -0.125rem -0.0625rem no-repeat;
  background-size: 12.9375rem 2.5625rem;
  width: 12.5rem;
  border: none;
}

.button:hover {
  background: url(../assets/img/module4/part1/SketchPng09fb34004ea1b0e5e91ff03feafa38bcb15201eba65a4db7b12083a8412bcc68.png) -0.125rem -0.0625rem no-repeat;
  height: 2.25rem;
  background-size: 12.9375rem 2.5625rem;
  width: 12.5rem;
  border: none;
}

.button.active {
  background: url(../assets/img/module4/part1/SketchPng09fb34004ea1b0e5e91ff03feafa38bcb15201eba65a4db7b12083a8412bcc68.png) -0.125rem -0.0625rem no-repeat;
  height: 2.25rem;
  background-size: 12.9375rem 2.5625rem;
  width: 12.5rem;
  border: none;
}

.text_button {
  width: 3rem;
  height: 1.5625rem;
  overflow-wrap: break-word;
  color: rgba(255, 255, 255, 1);
  font-size: 1rem;
  font-family: AlibabaPuHuiTi_2_75_SemiBold;
  text-align: center;
  white-space: nowrap;
  line-height: 1.5625rem;
  margin: 0.1875rem 0 0 4.15rem;
}

.layout2 {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.layout1 {
  display: flex;
  flex-direction: column;
  width: 50%;
  height: 100%;
  margin-top: 0.8125rem;
}

/* 顶部控制区域样式 */
.top-controls {
  display: flex;
  flex-direction: row;
  width: 100%;
  margin-bottom: 1rem;
  flex-grow: 1;
}

/* 模型选择区域样式 */
.model-selection {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
}

/* 表单容器样式调整 */
.form-container {
  display: flex;
  width: 100%;
  height: auto;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 0.25rem;
  border: 0.0625rem solid;
  margin-top: 0.375rem;
  flex-direction: column;
  margin-left: 1%;
  position: relative;
  flex-grow: 1;
}

.plat-form {
  height: 11.25rem;
  width: 90%;
  margin: 0.75rem 0 0 3.4375rem;
}

.title_plat {
  width: 12.125rem;
  height: 1.5625rem;
  /* margin: 1.5625rem 0 0 3.4375rem; */
  margin: 0.2rem 0 0 3.4375rem;
}

.image_1 {
  width: 1.5625rem;
  height: 0.9375rem;
  margin-top: 0.3125rem;
}

.text_form {
  width: 9.9375rem;
  height: 2.5625rem;
  overflow-wrap: break-word;
  color: rgba(255, 255, 255, 1);
  font-size: 1.125rem;
  font-family: AlibabaPuHuiTi_2_65_Medium;
  font-weight: NaN;
  text-align: left;
  white-space: nowrap;
  line-height: 25px;
  margin-left: 0.5rem;
}

/* 右侧区域样式 */
.right-section {
  width: 48%;
  height: 100%;
  margin-left: 2%;
}
</style>